package leetCode.solution;

import java.util.Arrays;

public class Solution16 {

	public int threeSumClosest(int[] nums, int target) {
		Arrays.sort(nums);
		int closestSum = nums[0] + nums[1] +nums[2];
		for(int i = 0;i<nums.length-2;i++) {
			int l = i+1,r = nums.length-1;
			while(l<r) {
				int threeSum = nums[i] + nums[l] +nums[r];
				closestSum = Math.abs(target-threeSum)<Math.abs(target-closestSum)?threeSum:closestSum;
				if(threeSum>target) {
					r-=1;
				}else if(threeSum<target) {
					l+=1;
				}else {
					return threeSum;
				}
			}
		}
		
		return closestSum;
    }
	
	public static void main(String[] args) {
		new Solution16().threeSumClosest(new int[] {-1,2,1,-4}, 1);
	}
}
